import router from './router';
import store from './store';
import user from './store/modules/user';
import { Message } from 'element-ui';
import NProgress from 'nprogress'; // progress bar
import 'nprogress/nprogress.css'; // progress bar style
import { getToken } from '@/utils/auth'; // get token from cookie
import getPageTitle from '@/utils/get-page-title';
import { getMenu } from './api/user';

import { addRouter } from './utils/addRouter';
NProgress.configure({ showSpinner: false }); // NProgress Configuration

const whiteList = ['/login']; // no redirect whitelist  '/auth-redirect'

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start();

  // set page title
  document.title = getPageTitle(to.meta.title);

  // determine whether the user has logged in
  const hasToken = getToken();

  /* 存在 token*/
  if (hasToken) {
    if (to.path !== '/login') {
      if (user.state.init) {
        // 获取了动态路由 data一定true,就无需再次请求 直接放行
        next();
      } else {
        await store.dispatch('user/getInfo');
        // data为false,一定没有获取动态路由,就跳转到获取动态路由的方法
        gotoRouter(to, next);
      }
    } else {
      Message({ message: '您已经登录', type: 'warning' });
      next('/');
    }
  } else {
    /* 没有 token*/
    if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      // next(`/login?redirect=${to.path}`);
      next('/login');
      NProgress.done();
    }
  }
});

router.afterEach(() => {
  // finish progress bar
  NProgress.done();
});

function gotoRouter(to, next) {
  const iRolesysnum = store.getters.iRolesysnum;
  getMenu({ iRolesysnum })
    .then(res => {
      const asyncRouter = addRouter(res.data); // 进行递归解析
      return asyncRouter;
    })
    .then(asyncRouter => {
      // 后置添加404页面,防止刷新404
      asyncRouter.push({
        path: '*',
        redirect: '/404',
        hidden: true
      });
      // if (process.env.NODE_ENV === 'development') {
      //   asyncRouter.push({
      //     path: '/lottery',
      //     component: () => import('@/layout'),
      //     meta: { title: '抽奖', icon: 'theme' },
      //     children: [
      //       {
      //         path: '/index',
      //         component: () => import('@/views/lotteryPage/index'),
      //         meta: {
      //           title: '抽奖'
      //         }
      //       }
      //     ]
      //   });
      // }
      router.options.routes = asyncRouter;
      router.addRoutes(asyncRouter); // vue-router提供的addRouter方法进行路由拼接
      // store.commit("user/SET_ROUTES", asyncRouter);
      store.dispatch('user/setRouterList', asyncRouter); // 存储到vuex
      // store.dispatch("user/GetInfo");
      store.commit('user/set_init', true);
      next({ ...to, replace: true }); // hack方法 确保addRoutes已完成
    });
}
